import { Button } from 'antd-mobile'
import { DownFill } from 'antd-mobile-icons'
import './home.less'
import bg from '@/assets/images/home/xiaolang.png'
import { useEffect, useState } from 'react'
import { homeDataApi } from '@/api'
import SubjectItem from './components/SbujectsItem'
import { useNavigate } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { changeSubject } from '@/store/userSlice'

// 从仓库里面取数据，就和之前差不多，
// useSelector 和 useDispatch 来获取的操作
export default function Home() {
  const dispatch = useDispatch();

  // 定义一个对象，把后端返回的数据存储起来
  const [state, setState] = useState<IHomeData>()

  useEffect(() => {
    homeDataApi().then(res => {
      if (res?.errCode === 0) {
        // 把 data 存起来
        setState(res.data)
        // 默认的学科存储到 redux 里面
        dispatch(changeSubject(res.data.exam.title))
      }
    })
  }, [])

  const nav = useNavigate()

  return <div className='home'>
    <div className="subjects flex flex-between">
      <h2>{state?.exam.title}</h2>
      <Button onClick={() => nav('/subjects')} color="primary" fill='none'>
        切换考试科目
        <DownFill />
      </Button>
    </div>
    <div className="wel">
      <div className="msg">欢迎Tomato来到XX学习库！</div>
      <div className="flex">
        <div className="left">
          <img src={bg} alt="" />
        </div>
        <div className="right">
          <ul className='flex'>
            <li>已学{state?.study}题</li>
            <li>共{state?.exam.itemCount}题</li>
          </ul>
          <ul className='flex'>
            <li className='flex'>
              <span className='num'>{state?.wrong}</span>
              <span className='text'>错题</span>
            </li>
            <li className='flex'>
              <span className='num'>{state?.collect}</span>
              <span className='text'>收藏</span>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <div className='sub-list'>
      <h2>学科题库</h2>
      <ul>
        {
          state?.exemItems.map(item => <SubjectItem data={item} key={item.id} />)
        }
      </ul>
    </div>
  </div>
}

